package com.demo2do.boyle.backend.web.controller.customer;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.demo2do.boyle.backend.service.customer.ImportExcelService;
import com.demo2do.core.entity.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.interceptor.MenuSetting;

/**
 * 
 * @author Jason.Y
 */
@Controller
@RequestMapping("/customers")
@MenuSetting("menu-customer")
public class ImportExcelCustomerController {

	private static final Logger logger = LoggerFactory.getLogger(ImportExcelCustomerController.class);
	
    @Autowired
    private ImportExcelService importExcelService;
    
    /**
     * list all customers
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/importExcel", method=RequestMethod.PATCH)
    @MenuSetting("submenu-customer-list")
    public void importExcel(@RequestParam("excelFile") MultipartFile excelFile,
    		@RequestParam(value = "_method", required = false) String _method,HttpServletResponse response) {
    	
		Result result = new Result();
		PrintWriter out = null;
		StringBuffer sb = new StringBuffer();
		try {
			out = response.getWriter();
			result = importExcelService.resolveExcel(excelFile,sb);
			out.print(JsonUtils.toJsonString(result));

		} catch (Exception e) {
			if(sb.length() != 0){
				result.fail().message(sb.toString());
				out.print(JsonUtils.toJsonString(result));
			}
			logger.error(e.getMessage());
		}
	}

}
